/**
 * Created by 追风少年 on 2018/6/7.
 */

var ServiceProviderInput = {
    URL:{
        UPLOAD_IMG_URL:'/admin/upload/serviceProvider',
        ADD_URL:'/admin/serviceProvider/add',
        UPDATE_URL:'/admin/serviceProvider/update',
        GET_TYPE_LIST_URL:'/admin/serviceModel/findList',
        GET_AREA_LIST_URL:'/admin/serviceProvider/getArea',
        FIND_ONE_URL:"/admin/serviceProvider/findById"
    }
};

layui.use('upload', function() {
    var $ = layui.jquery
        , upload = layui.upload;

    //上传服务商营业执照照片
    var licenseImgUpload = upload.render({
        elem: '#licenseImgUploadBtn'
        , url: ServiceProviderInput.URL.UPLOAD_IMG_URL

        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#licenseImg').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status) {
                // 上传成功
                console.log("上传成功");
                console.log(res);
                $("#img_license").val(res.data);
            }else{
                return layer.msg('上传失败');
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#licenseImgUploadCue');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    //上传服务商资质照片
    var qualificationImgUpload = upload.render({
        elem: '#qualificationImgUploadBtn'
        , url: ServiceProviderInput.URL.UPLOAD_IMG_URL
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#qualificationImg').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.status) {
                // 上传成功
                console.log("上传成功");
                console.log(res);
                $("#img_qualification").val(res.data);
            }else{
                return layer.msg('上传失败');
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#licenseImgUploadCue');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

});

app.controller('inputServiceProviderController', function($scope,$http,$q) {

    $scope.flowTypeList = [];

    $scope.entity = {
        service_name:"",
        service_type:"1",
        service_area:"",
        contact_mobile:"",
        contact_name:"",
        service_status:"1",
        flow_type:"",
        flow_type_name:"",
        img_license:"",
        img_qualification:"",
        service_intro:"",
        service_website:"",
        account_name:"",
        account_idnumber:"",
        account_bank:"",
        account_bank_no:"",
        account_type:"1"
    };
    $scope.submitUrl = ServiceProviderInput.URL.ADD_URL;

    $scope.serviceAreaList = [];

    $scope.areaList = [];

    // 页面加载完成
    $scope.load = function(){
        var id = $("#serviceId").val();
        if(id != "none"){ // is update page
            $scope.submitUrl = ServiceProviderInput.URL.UPDATE_URL;
        }
    };

    $scope.validateParam = function(){
        if(Utils.isNull($scope.entity.img_license)){
            $scope.entity.img_license = $("#img_license").val();
        }
        if(Utils.isNull($scope.entity.img_qualification)){
            $scope.entity.img_qualification = $("#img_qualification").val();
        }
        $scope.entity.service_status = $("input[name='status']:checked").val();
        $scope.entity.account_type = $("input[name='account_type']:checked").val();
        $scope.entity.service_type = $("input[name='service_type']:checked").val();

        if(Utils.isNull($scope.entity.service_name)){
            layer.msg("请填写服务商全称");
            return false;
        }
        if(Utils.isNull($scope.entity.contact_name)){
            layer.msg("请填写联系人姓名");
            return false;
        }
        if(Utils.isNull($scope.entity.account_name)){
            layer.msg("请填写收款人名称");
            return false;
        }
        if(Utils.isNull($scope.entity.account_idnumber)){
            layer.msg("请填写收款人证件号");
            return false;
        }
        if(Utils.isNull($scope.entity.account_bank)){
            layer.msg("请填写收款银行");
            return false;
        }
        if(Utils.isNull($scope.entity.account_bank_no)){
            layer.msg("请填写收款银行帐号");
            return false;
        }
        if(Utils.isNull($scope.entity.service_intro)){
            layer.msg("请填写服务商介绍");
            return false;
        }
        if(Utils.isNull($scope.entity.service_website)){
            layer.msg("请填写门户网站");
            return false;
        }
        if(!Utils.validateMobile($scope.entity.contact_mobile)){
            layer.msg("联系人手机格式错误");
            return false;
        }

        var types = Utils.getCheckBoxNameAndVal("serviceType");
        $scope.entity.flow_type = "";
        $scope.entity.flow_type_name = "";
        for (var i = 0; i < types.length; i++){
            if(i>0){
                $scope.entity.flow_type += ",";
                $scope.entity.flow_type_name += ",";
            }
            $scope.entity.flow_type += types[i].value;
            $scope.entity.flow_type_name += types[i].name;
        }
        if(types.length == 0){
            layer.msg("请选择供应商服务类型");
            return false;
        }
        $scope.entity.service_area = "";
        for(var i = 0; i < $scope.serviceAreaList.length; i++){
            if(i > 0){
                $scope.entity.service_area += ",";
            }
            $scope.entity.service_area += $scope.serviceAreaList[i];
        }
        if(Utils.isNull($scope.entity.service_area)){
            layer.msg("请选择供应商服务范围");
            return false;
        }
        if(Utils.isNull($scope.entity.img_license)){
            layer.msg("请上传服务商营业执照照片");
            return false;
        }
        if(Utils.isNull($scope.entity.img_qualification)){
            layer.msg("请上传服务商资质照片");
            return false;
        }
        return true;
    };

    $scope.submit = function($event){
        if(!$scope.validateParam()){ // 校验参数
            return false;
        }
        var btn = $event.target;
        btn.disabled = true;
        $http.post($scope.submitUrl,$scope.entity).success(function (ret) {
            console.log(ret);
            if(ret.status){
                layer.alert(ret.msg, {
                    icon: 1,
                    skin: 'layer-ext-moon',
                    yes:function(index){
                        layer.close(index);
                        parent.closeWinAndFlush();
                    }
                });
            }else{
                btn.disabled = false;
                return;
            }
        }).error(function(ret){
            btn.disabled = false;
            console.error("err:"+ret);
        });

    };

    /**  页面数据加载  **/

    /**
     * 获取服务类型
     */
    function getServiceModelList() {
        return $q(function (resolve, reject) {
            $http.post(ServiceProviderInput.URL.GET_TYPE_LIST_URL,{}).success(function(data,status,headers,config){
                console.log(data);
                if(data.status){
                    // var serviceNames = data.data.map(function(v){return v.service_name;});
                    $scope.flowTypeList = data.data;
                    resolve("getServiceModelList successful");
                }else{
                    console.error(data);
                    reject("getServiceModelList fail");
                    alert("数据加载失败,请联系管理员");
                }
            }).error(function(data,status,headers,config){
                console.error(data);
                reject("getServiceModelList fail");
            });
        })
    }

    /**
     * 获取地区数据
     */
    function getAreaData() {
        return $q(function (resolve, reject) {
            $http.post(ServiceProviderInput.URL.GET_AREA_LIST_URL,{}).success(function(data,status,headers,config){
                if(data.status){
                    // var serviceNames = data.data.map(function(v){return v.service_name;});
                    $scope.areaList = data.data;
                    resolve("getAreaData successful");
                }else{
                    console.error(data);
                    reject("getAreaData fail");
                    alert("数据加载失败,请联系管理员");
                }
            }).error(function(data,status,headers,config){
                console.error(data);
                reject("getAreaData fail");
            });
        })
    }

    /**
     * 获取编辑的数据信息
     */
    function getEntityInfo() {
        return $q(function (resolve, reject) {
            var id = $("#serviceId").val();
            if(id == "none"){
                resolve("getUserInfo successful");
                return false;
            }
            $http.post(ServiceProviderInput.URL.FIND_ONE_URL,{id:id}).success(function(data,status,headers,config){
                // console.log("数据请求成功");
                // console.log(data);
                if(data.status){
                    $scope.entity = data.data;
                    $scope.serviceAreaList = $scope.entity.service_area.split(",");
                    resolve("getEntityInfo successful");
                }else{
                    console.error(data);
                    reject("getEntityInfo fail");
                    alert("数据加载失败,请联系管理员");
                }
            }).error(function(data,status,headers,config){
                console.error(data);
                reject("getEntityInfo fail");
            });
        });
    }

    /**
     * 初始化模块多选框
     */
    function initServiceModelCheckbox(){
        var checkBoxDiv = $("#serviceTypeDiv");
        var selectedFlowTypeArr = [];
        if(!Utils.isNull($scope.entity.flow_type)){
            selectedFlowTypeArr = $scope.entity.flow_type.split(",");
        }
        for(var i = 0; i < $scope.flowTypeList.length; i++){
            var checked = false;
            var type = $scope.flowTypeList[i];
            for (var j = 0; j < selectedFlowTypeArr.length; j++){
                if(selectedFlowTypeArr[j] == type.id){
                    checked = true;
                    break;
                }
            }
            if(checked){
                checkBoxDiv.append('<input checked="" value="'+type.id+'" type="checkbox" name="serviceType" title="'+type.service_name+'">');
            }else{
                checkBoxDiv.append('<input value="'+type.id+'" type="checkbox" name="serviceType" title="'+type.service_name+'">');
            }
        }
    }

    /**
     * 初始化地区选择
     */
    function initAreaSelect(){
        var select = $("#serviceArea");
        for(var i = 0; i < $scope.areaList.length; i++){
            var o = $scope.areaList[i];
            select.append('<option value="'+o._key+'">'+o._key+'</option>');
        }
    }

    /**
     * 选择地区
     * @param data
     */
    $scope.putArea = function(data){
        if($scope.serviceAreaList.length == 0){
            $scope.serviceAreaList.push(data.value);
        }else{
            var needPut = true;
            for(var i = 0; i<$scope.serviceAreaList.length;i++){
                if($scope.serviceAreaList[i]==data.value){
                    needPut = false;
                    break;
                }
            }
            if(needPut) $scope.serviceAreaList.push(data.value);
        }
        $scope.$apply();
    };

    /**
     * 所有数据加载完成后执行
     */
    $q.all([getServiceModelList(), getEntityInfo(), getAreaData()]).then(function (dataArr) {
            //promise都成功执行后的回调函数
            initServiceModelCheckbox();
            initAreaSelect();
            layui.use('form', function(){
                var form = layui.form;
                form.render('checkbox');
                form.render('select');
                form.on('select(serviceArea)', function(data){
                    $scope.putArea(data);
                });
            });
    }, function (err) {
        console.log("$q.all: ", err);
        alert("数据加载失败");
    });

    $scope.delArea = function(index){
        $scope.serviceAreaList.splice(index,1);
    };

});